package com.gaofans.nrpc.client.route;

import com.gaofans.nrpc.common.processor.CommonEventProcessor;
import com.gaofans.nrpc.common.processor.EventListener;

import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author GaoFans
 */
public abstract class ServiceStorage {

    private final CommonEventProcessor<ServiceEvent<ServiceInstance>,String> processor;

    public ServiceStorage() {
        this.processor = new CommonEventProcessor<>();
    }

    /**
     * 获取全部
     * @param serviceId
     * @return
     */
    public abstract List<ServiceInstance> getInstances(String serviceId);

    /**
     * 返回全部的serviceId
     * @return
     */
    public abstract List<String> services();

    /**
     * 添加事件监听
     * @param listener
     */
    public void addListener(String listenerName,EventListener<ServiceEvent<ServiceInstance>> listener){
        processor.register(listenerName,listener);
    }

    protected void publish(String name, ServiceInstance instance, ServiceEvent.EventType type){
        processor.get(name).onDataChunk(new ServiceEvent<>(type,instance));
    }

    protected void publishAll(ServiceInstance instance, ServiceEvent.EventType type){
        Set<Map.Entry<String, EventListener<ServiceEvent<ServiceInstance>>>> entries = processor.all().entrySet();
        for (Map.Entry<String, EventListener<ServiceEvent<ServiceInstance>>> entry : entries) {
            entry.getValue().onDataChunk(new ServiceEvent<>(type,instance));
        }
    }

}
